<template>
    
    <!-- 组件的模板 -->
    <div class="page">
        <form>
            <div class="item flex">
                <input v-on:input="veriryPhoneFormat" v-model="formData.phone" :value="formData.phone" id="regiPhone" type="tel" maxlength="11" placeholder="手机号码" >
            </div>
            <div class="item flex">
                <input v-model="formData.vCode" id="regiVcode" type="tel" class="input-text" maxlength="6" placeholder="验证码（6位）" :value="formData.vCode">
                <span v-if="formData.phone.length == 11" class="get-code flex active" @click="getVCode" v-show="!isCounting" id="getvCode"><span v-if="spacewhite">&nbsp;&nbsp;&nbsp;&nbsp;</span>{{countingTxt}}</span>
                <span v-else class="get-code flex" :disabled="!vCodeActive"  v-show="!isCounting" id="getvCode"><span v-if="spacewhite">&nbsp;&nbsp;&nbsp;&nbsp;</span>{{countingTxt}}</span>
                <span v-else class="get-code flex" @click="getVCode"  v-show="isCounting" :disabled="isCounting">{{countingTxt2}}</span>
            </div>              
            <a href="javascript:;" id="registerBtn" class="weui-btn weui-btn_primary" @click="doLogin" v-if = "formData.phone && formData.vCode">登 录</a>            
            <a href="javascript:;" id="registerBtn" class="weui-btn weui-btn_disabled weui-btn_primary" v-else>登 录</a>            
        </form>
        <div class="link">
            <span><a @click="passwordLogin">密码登录</a></span>
            <a href="dmsaas://CodeIntroduce">收不到验证码</a>
        </div>
    </div>
    <!-- 第三方登录 -->
    <div class="another_login" @click="bindPhone" v-show="thirdloginLogo">
      <div class="login_tip">
          <span class="before_tip"></span>
          <span class="another_logintip">其他登录方式</span>
          <span class="after_tip"></span>
      </div>
      <img class="login_image" src="../../static/imgs/weixin.png" alt="">
    </div>
    <!-- 验证图片 -->
    <div class="mod-popup popup-robot-check" v-show="showRobotPopup">
      <div class="mod-popup-head hide">确认你不是机器人</div>
      <div class="mod-popup-body">
        <div class="robot-avatar"></div>
        <div class="form-tips">请输入图片验证码确认你不是机器人：</div>
        <div class="form-field">
          <div class="form-item">
            <label class="form-label">验证码</label>
            <div class="form-control">
              <div class="multi-group">
                <label class="input-group">
                  <input v-model="imgCode" id="picCode" type="text" class="input-text" placeholder="请输入验证码">
                </label>
                <div class="code-group">
                  <img id="verify_code_image" v-bind:src="base64ImgData" alt=""><i @click="refreshImg" class="icon-refresh">刷新</i>
                </div>
              </div>
            </div>
          </div>
          <div class="form-warning-picode" v-show="invalidImgCode">{{imgCodeErrMsg}}</div>
        </div>
        <div class="mod-popup-btn-box">
          <button @click="submitImgCode" id="picCodeSureBtn" class="btn btn-primary btn-large js-touch-state">确认</button>
          <button @click="cancelRobotPopup" id="picCodeCancelBtn" class="btn btn-link btn-large js-touch-state">取消</button>
        </div>
      </div>
    </div>   
</template>

<script>
    let receiveImgcode = true
    let thridloginData
    /**
     *  引入工具类库 或 Native API
     *  example : import widget from 'gapi/widget'
     */
    import $ from 'zepto'
    import userCenterApi from 'clientApi/userCenterApi'
    import clientInfo from 'gapi/clientInfo'
    import safety from 'gapi/safety'
    import widget from 'gapi/widget.js'  
    import * as util from 'js/util.js'
    import commonPage from 'clientApi/commonPage.js'
    import clientUtil from 'clientApi/util' 
    /**
     *  引入组件 以及 组件接口(Action)
     *  example : import Somecomponents from 'components/Somecomponents/Somecomponents'
     */

    /**
     *  组件实例对象
     */
    export default {
        components: {

        },
        data: function(){
            return{
                formData: {},
                isCounting: false,
                countingTxt: '获取验证码',
                countingTxt2: '',
                spacewhite: false,
                thridloginData: '',
                thirdloginLogo: true,
                bindPhoneData: {},
            }
        },
        vuex: {
            getters: {

            },
            actions: {

            }
        },
        methods: {
            /**
             * 初始化
             * @method init
             * @public
             * @return {Null} void
             */
            init (){         
                let that = this  
                if(clientUtil.OS() == 'android'){
                  let clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
                  $(window).on('resize', function () {
                      let nowClientHeight = document.documentElement.clientHeight || document.body.clientHeight;
                      if (clientHeight > nowClientHeight) {
                          //键盘弹出的事件处理
                           that.thirdloginLogo = false
                      }
                      else {
                          //键盘收起的事件处理
                           setTimeout(() => {                              
                              that.thirdloginLogo = true
                           }, 500)
                      }
                  })
                }else{
                    userCenterApi.weixinIsInstall(data => {
                      if(data.status == 1){
                          $(document).on('focusin', function () {
          　　                //软键盘弹出的事件处理
                              that.thirdloginLogo = false
                          });
                          $(document).on('focusout', function () {
                          　　//软键盘收起的事件处理
                            setTimeout(() => {                              
                                that.thirdloginLogo = true
                            }, 1000)
                          });                        
                      }else{
                          that.thirdloginLogo = false
                      }

                    })
                    
                }
                

                  
            },
            /**
            * 监听验证手机格式, 激活手机验证码按钮
            **/
            veriryPhoneFormat () {
                const phone = this.formData.phone;
                const phoneIsValid = /^\d{11}$/.test(phone);
                this.vCodeActive = phoneIsValid ? true : false;
            },
            /**
            * 获取手机验证码
            **/
            getVCode (){             
              if(!receiveImgcode){
                  return
              }
              receiveImgcode = false

              //防止双击事件
              setTimeout(function(){
                receiveImgcode = true
              }, 1000)
                

                this.vCodeActive = false
                let apiUrl = "";
                let headers = {}
                clientInfo.getNetworkType(data => {
                  if (data.network != 'invalid') {
                    userCenterApi.getHost(data => {
                      apiUrl =  data.info + clientUtil.getApiPath() + '/authCkCode'//todo:encapsule
                      clientInfo.getCommonHeaders(data => {
                        headers = data;
                        $.ajax({
                          url: apiUrl ,
                          type: 'POST',
                          dataType: 'json',
                          data: {
                            mobile: this.formData.phone,
                            platform: clientUtil.OS(),
                            token: ''
                          },
                          timeout: 10000,
                          headers: headers,
                          success: data => {//手机验证码发送成功
                            this.isCounting = true; //show countdown button
                            this.countDown(60); //counting down
                          },
                          error: (xhr, status) => {
                            if (status == 'timeout'){
                              widget.toast('网络请求超时');
                            }else{
                                  if(xhr.status==400){
                                      let err=JSON.parse(xhr.responseText);
                                      if(err.code===-3){//显示图片验证码浮层 
                                          userCenterApi.showCodeDialog(this.formData.phone, data => {
                                            if(data.status == 1){ 
                                              this.isCounting = true; 
                                              this.countDown(60);                           
                                            }
                                          })
                                        
                                        // this.showRobotPopup = true
                                        // //reset 
                                        // this.invalidImgCode = false
                                        // this.imgCode = ''
                                        // this.base64ImgData = ''
                                        // // util.commonOptions(t,clientInfo,t.getPic,picData[1]);
                                        // this.getCaptcha()//获取图片验证码
                                      }else{
                                          // receiveImgcode = true
                                          widget.toast(err.message);
                                          
                                      }
                                  }else{
                                      // receiveImgcode = true
                                      this.vCodeActive = true;
                                      widget.toast('服务器异常');
                                  }
                              }
                          }
                       })  
                      })
                      
                    })
                  } else {
                    this.vCodeActive = true;
                    widget.toast('网络连接失败，请检查网络')
                  }
                })
            },
            /**
            * 倒计时
            **/
            countDown (seconds){
              this.isCounting = true
              this.countingTxt2 = ''
              let _seconds = seconds;
              let tId;
              receiveImgcode = false
              
              tId = setInterval(() => {
                if (_seconds == 0){
                  clearInterval(tId);
                  this.isCounting = false
                  this.countingTxt = ' 重新获取'
                  this.vCodeActive = true;
                  receiveImgcode = true
                  this.spacewhite = true
                }else{
                  _seconds--;
                  this.countingTxt2 = `${_seconds}秒后重发`
                }
              }, 1000)
            },
            /**
            * 获取图片验证码图片
            **/
            getCaptcha (){
                let apiUrl = ""//todo 
                let headers = {}
               clientInfo.getNetworkType(data => {
                  if (data.network != 'invalid') {
                    userCenterApi.getHost(data => {
                      apiUrl =  data.info + clientUtil.getApiPath() + '/ajax/encodedcode'
                      clientInfo.getCommonHeaders(data => {
                        headers = data;
                        $.ajax({
                          url: apiUrl ,
                          type: 'GET',
                          dataType: 'json',
                          data: {
                            platform: clientUtil.OS(),
                            token: ''
                          },
                          timeout: 10000,
                          headers: headers,
                          success: data => {
                            if(!!data && !!data.pic_code){
                              this.base64ImgData = data.pic_code
                        }else{
                            widget.toast('服务器异常');
                        }
                          },
                          error: (xhr, status) => {
                            // util.ajaxErrorFn(widget,xhr,status,true,UCApi);
                          }
                       })  
                      })
                      
                    })
                  } else {
                      widget.toast('网络连接失败，请检查网络');
                  }
                })
            },
            /**
            * 刷新图片验证码
            **/
            refreshImg (){
              this.getVCode()
            },
            /**
            * 提交图片验证码
            **/
            submitImgCode (){
              let apiUrl = ""
              let headers = {}
              this.invalidImgCode = false
              if(!this.imgCode){
                this.invalidImgCode = true
                this.imgCodeErrMsg = '请输入正确的图片验证码'
                return;
              }
                clientInfo.getNetworkType(data => {
                  if (data.network != 'invalid') {
                    userCenterApi.getHost(data => {
                      apiUrl =  data.info + clientUtil.getApiPath() + '/authCkCode'//todo:encapsule
                      clientInfo.getCommonHeaders(data => {
                        headers = data;
                        $.ajax({
                          url: apiUrl ,
                          type: 'POST',
                          dataType: 'json',
                          data: {
                            mobile: this.formData.phone,
                            platform: clientUtil.OS(),
                            code : imageCode,
                            token: ''
                          },
                          timeout: 10000,
                          headers: headers,
                          success: data => {//图片验证码
                            // this.showRobotPopup = false;
                            this.isCounting = true; 
                            this.countDown(60); 
                          },
                          error: (xhr, status) => {
                            if (status == 'timeout'){
                              widget.toast('网络请求超时');
                            }else{
                                  if(xhr.status==400){
                                    //xhr.responseText.code : -4 -> 图片验证码错误; -206: 一分钟内不能获取验证码  
                                    this.invalidImgCode = true
                                    this.imgCodeErrMsg = JSON.parse(xhr.responseText).message
                                  }else{
                                      widget.toast('服务器异常');
                                  }
                              }
                          }
                       })  
                      })
                      
                    })
                  } else {
                    widget.toast('网络连接失败，请检查网络');
                  }
                })
            },
            /**
            * 点击取消按钮, 关闭图片验证码弹框
            **/
            cancelRobotPopup (){
              this.showRobotPopup = false;
              this.vCodeActive = true;
            },
            doLogin (){
                // this.hasError = true;
                //表单校验 todo: migrate to vue-validator
                if (!this.formData.phone){
                    widget.toast('请输入手机号') 
                    return
                }else if (this.formData.phone.length != 11){
                    widget.toast('请输入正确的手机号')
                    return
                }else if (!this.formData.vCode){ 
                    widget.toast('验证码不能为空')
                    return                    
                }else if (!/^\d{6}$/.test(this.formData.vCode)){ //非6位数字 
                    widget.toast('验证码错误')
                    return                    
                } else {
                    // this.hasError = false
                    // this.errMsg = ""
                    //调用客户端加密Api todo 变量作用域
                    commonPage.loadPageStatus('loading')
                    // safety.dekEncrypt(this.formData.password, info => {
                      // const encryptPwd = info;
                      //调用客户端登陆Api
                      userCenterApi.logIn(this.formData.phone, this.formData.vCode, '', {}, data => {
                        commonPage.loadPageStatus('loadSuccess')
                        if(!!data){                   
                          console.log("errorMessage"+data.code);
                          if (data.code == -201) {
                            widget.toast(data.message);
                          }else if(data.code == -313) {
                            widget.toast('当前用户未注册，请直接注册');
                          }else if(data.code == -312) {
                            widget.toast('密码错误，请点忘记密码进行重置');
                          }else{
                            widget.toast(data.message);
                          }
                        }
                        // Native toast: 密码错误 or  未注册
                      })
                    // })
              }
            },
            //切换到密码登录
            passwordLogin (){
              location.href = 'dmsaas://Login?urdData=' + encodeURIComponent(`phoneNumber=${this.formData.phone}`)
            },
            //第三方登录
            bindPhone (){
              let that = this
               userCenterApi.thirdPartyLogin(data =>{

               })
            }
        },
        created(){

            this.init();
            
        }
        
    }

    
</script>

<!-- CSS 样式 -->
<!-- <style src="static/css/global.css"></style> -->
<style src="../../node_modules/weui/dist/style/weui.css"></style>
<style src="../../static/css/global.css"></style>
<style src="../../static/css/login.css"></style>
<style src="../../static/css/form.css"></style>
<style src="../../static/css/account.css"></style>
<style src="../../static/css/common.css"></style>
<style src="../../static/css/login-register.css"></style>
<style>
  body{
    background: #fff!important;
  }
  .input-text{
    text-align: left!important;
  }
  ::-webkit-input-placeholder {
    color: #bbb!important;
  }
  .dialog__btn_primary {
    color: black!important;
  }
  .page{

  }

</style>



